﻿using DevExpress.XtraEditors;
using Lamex.Base;
using Lamex.Interface;
using Lamex.Library;
using Lamex.Library.CommonClass;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Lamex.mDashboard.UI
{
    public partial class FrmMCG_Powder_Coating : frmBaseChild
    {
        DataTable Table_Sum;
        DataTable Table_Detail;
        string HNI_Months = "";
        public FrmMCG_Powder_Coating()
        {
            InitializeComponent();
        }

        private void FrmMCG_Powder_Coating_Load(object sender, EventArgs e)
        {
            try { base.InitButtons(); } catch { }//初始化标准功能，因要应用于RibbonForm，所以加入异常处理

            //HNI月显示
            this.dateEdit1.Properties.DisplayFormat.FormatString = "yyyyMM";
            this.dateEdit1.Properties.DisplayFormat.FormatType = DevExpress.Utils.FormatType.DateTime;
            this.dateEdit1.Properties.EditFormat.FormatString = "yyyyMM";
            this.dateEdit1.Properties.EditFormat.FormatType = DevExpress.Utils.FormatType.DateTime;
            this.dateEdit1.Properties.Mask.EditMask = "yyyyMM";
            this.dateEdit1.Properties.VistaCalendarInitialViewStyle = DevExpress.XtraEditors.VistaCalendarInitialViewStyle.YearView;
            this.dateEdit1.Properties.VistaCalendarViewStyle = DevExpress.XtraEditors.VistaCalendarViewStyle.YearView;
            //显示底部数据导航器
            gridControl1.UseEmbeddedNavigator = true;
            gridControl2.UseEmbeddedNavigator = true;
        }

        private void FrmMCG_Powder_Coating_Resize(object sender, EventArgs e)
        {
            gridControl1.Width = this.panelControl2.Width / 2;
            gridControl2.Width = this.panelControl2.Width / 2;
        }

        private void dateEdit1_EditValueChanged(object sender, EventArgs e)
        {
            string dateHNI_Now = dateEdit1.Text.Trim();
            if (!string.IsNullOrEmpty(dateHNI_Now))
            {
                string datetimeHNI = dateHNI_Now.Substring(0, 4) + "-" + dateHNI_Now.Substring(4, 2) + "-01";
                string dateHNI_Next = Convert.ToDateTime(datetimeHNI).AddMonths(1).ToString("yyyyMM");
                string date_Start = "", date_End = "";
                date_Start = Common.CURDHelper.GetHNIFirst_Day(dateHNI_Now);
                date_End = Common.CURDHelper.GetHNIFirst_Day(dateHNI_Next);
                if (string.IsNullOrEmpty(date_Start) || string.IsNullOrEmpty(date_End))
                {
                    DevExpress.XtraEditors.XtraMessageBox.Show("HNI日历没有维护！,请联系管理员维护信息！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    txtStart.Text = "";
                    txtEnd.Text = "";
                    dateEdit1.Text = "";
                    gridControl1.DataSource = new DataTable();
                    gridControl2.DataSource = new DataTable();
                    Table_Sum = new DataTable();
                    Table_Detail = new DataTable();
                    txtQty.Text = "";
                    HNI_Months = "";
                    return;
                }
                txtStart.Text = Convert.ToDateTime(date_Start).ToString("yyyy-MM-dd");
                txtEnd.Text = Convert.ToDateTime(date_End).AddDays(-1).ToString("yyyy-MM-dd");
            }
        }
        public override void DoView(IButtonInfo sender)
        {
            try
            {
               
                string strStart = txtStart.Text;
                string strEnd = txtEnd.Text;
                HNI_Months = dateEdit1.Text;
                if (string.IsNullOrEmpty(HNI_Months) || string.IsNullOrEmpty(strStart) || string.IsNullOrEmpty(strEnd))
                {
                    DevExpress.XtraEditors.XtraMessageBox.Show("HNI时间不允许为空！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
                SplashScreenTool.ShowSplashScreen(typeof(WaitForm1));
                //生成临时表
                DataTable dt_Temp = Common.GetTable.GetTable_MCG_PowderCoating();
                DateTime dt1 = Convert.ToDateTime(strStart);
                DateTime dt2 = Convert.ToDateTime(strEnd);
                //初始化
                gridControl1.DataSource = dt_Temp;
                gridControl2.DataSource = new DataTable();
                Table_Sum = new DataTable();
                Table_Detail = new DataTable();
                txtQty.Text = "";
                //判断是否存在当月的HNI数据
                DataTable table_History = Common.CURDHelper.GetTable_Productivity_History(HNI_Months);
                if (table_History.Rows.Count > 0)
                {
                    //铝材明细表
                    DataTable dt_Aluminium = Common.CURDHelper.GetTable_Aluminium(strStart, strEnd);
                    //直接查数据库显示
                    //获取生产力总数
                    double total_Alum = table_History.AsEnumerable().Select(d => Convert.ToDouble(d.Field<decimal?>("ALUMINIUM_QTY"))).Sum();
                    double total_Convert = table_History.AsEnumerable().Select(d => Convert.ToDouble(d.Field<decimal?>("MC_CONVERT_QTY"))).Sum();
                    double total_WorkHour = table_History.AsEnumerable().Select(d => Convert.ToDouble(d.Field<decimal?>("WORK_HOURS"))).Sum();
                    if (total_WorkHour > 0)
                        txtQty.Text = Math.Round((total_Alum + total_Convert) / total_WorkHour, 2).ToString();
                    gridControl1.DataSource = table_History;
                    gridControl2.DataSource = dt_Aluminium;
                    TotalSum();
                    Table_Sum = table_History;
                    Table_Detail = dt_Aluminium;
                }
                else
                {
                    //临时表赋值
                    while (dt1 <= dt2)
                    {
                        DataRow dr = dt_Temp.NewRow();
                        dr["WORK_DATE"] = dt1.ToString("yyyy-MM-dd");
                        dr["ALUMINIUM_QTY"] = (object)DBNull.Value;
                        dr["METAL_CABINET_QTY"] = (object)DBNull.Value;
                        dr["MC_CONVERT_QTY"] = (object)DBNull.Value;
                        dr["WORK_HOURS"] = (object)DBNull.Value;
                        dr["PRODUCTIVITY"] = (object)DBNull.Value;
                        dt1 = dt1.AddDays(1);
                        dt_Temp.Rows.Add(dr);
                    }
                    //铝材数量
                    DataTable dt_Aluminium = Common.CURDHelper.GetTable_Aluminium(strStart, strEnd);//铝材明细表
                    DataTable dt_AluminTemp = Common.GetTable.GetTable_Alumin();
                    if (dt_Aluminium.Rows.Count > 0)
                    {
                        dt_AluminTemp = dt_Aluminium.AsEnumerable().GroupBy(r => new { Scn_Date = r["Scn_Date"] }).Select(
                        g =>
                        {
                            var row = dt_AluminTemp.NewRow();

                            row["WORK_DATE"] = g.Key.Scn_Date;
                            row["ALUMINIUM_QTY"] = g.Sum(r => (decimal)r["Part_QTY"]);
                            return row;
                        }).CopyToDataTable();
                    }
                    dt_Temp = Common.DataTableHelper.MergeTabel1(dt_Temp, dt_AluminTemp, "WORK_DATE");

                    //钢柜数量
                    DataTable dt_METAL_CABINET = Common.CURDHelper.GetTable_METAL_CABINET(strStart, strEnd);
                    dt_Temp = Common.DataTableHelper.MergeTabel2(dt_Temp, dt_METAL_CABINET, "WORK_DATE");

                    //喷粉工时+生产力
                    DataTable dt_WORK_HOUR = Common.CURDHelper.GetTable_Work_Hours(strStart, strEnd);
                    dt_WORK_HOUR = Common.DataTableHelper.MergeTabel3(dt_Temp, dt_WORK_HOUR, "WORK_DATE");

                    //获取生产力总数
                    double total_Alum = dt_Temp.AsEnumerable().Select(d => Convert.ToDouble(d.Field<string>("ALUMINIUM_QTY"))).Sum();
                    double total_Convert = dt_Temp.AsEnumerable().Select(d => Convert.ToDouble(d.Field<string>("MC_CONVERT_QTY"))).Sum();
                    double total_WorkHour = dt_Temp.AsEnumerable().Select(d => Convert.ToDouble(d.Field<string>("WORK_HOURS"))).Sum();
                    if (total_WorkHour > 0)
                        txtQty.Text = Math.Round((total_Alum + total_Convert) / total_WorkHour, 2).ToString();
                    gridControl1.DataSource = dt_Temp;
                    gridControl2.DataSource = dt_Aluminium;
                    TotalSum();
                    Table_Sum = dt_Temp;
                    Table_Detail = dt_Aluminium;

                }
                SplashScreenTool.CloseSplashScreen();
            }
            catch (Exception ex)
            {
                SplashScreenTool.CloseSplashScreen();
                XtraMessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
        }
        private void TotalSum()
        {
            gridView1.Columns[0].SummaryItem.SummaryType = DevExpress.Data.SummaryItemType.Count;
            gridView1.Columns[0].SummaryItem.DisplayFormat = "合计：";

            if (gridView1.Columns.Contains(gridView1.Columns["ALUMINIUM_QTY"]))
            {
                gridView1.Columns["ALUMINIUM_QTY"].SummaryItem.SummaryType = DevExpress.Data.SummaryItemType.Sum;
                this.gridView1.Columns["ALUMINIUM_QTY"].SummaryItem.DisplayFormat = "{0:N}";
            }
            if (gridView1.Columns.Contains(gridView1.Columns["METAL_CABINET_QTY"]))
            {
                gridView1.Columns["METAL_CABINET_QTY"].SummaryItem.SummaryType = DevExpress.Data.SummaryItemType.Sum;
                this.gridView1.Columns["METAL_CABINET_QTY"].SummaryItem.DisplayFormat = "{0:N}";
            }
            if (gridView1.Columns.Contains(gridView1.Columns["MC_CONVERT_QTY"]))
            {
                gridView1.Columns["MC_CONVERT_QTY"].SummaryItem.SummaryType = DevExpress.Data.SummaryItemType.Sum;
                this.gridView1.Columns["MC_CONVERT_QTY"].SummaryItem.DisplayFormat = "{0:N}";
            }
            if (gridView1.Columns.Contains(gridView1.Columns["WORK_HOURS"]))
            {
                gridView1.Columns["WORK_HOURS"].SummaryItem.SummaryType = DevExpress.Data.SummaryItemType.Sum;
                this.gridView1.Columns["WORK_HOURS"].SummaryItem.DisplayFormat = "{0:N}";
            }
            if (gridView1.Columns.Contains(gridView1.Columns["PRODUCTIVITY"]))
            {
                //gridView1.Columns["PRODUCTIVITY"].SummaryItem.SummaryType = DevExpress.Data.SummaryItemType.Sum;
                //this.gridView1.Columns["PRODUCTIVITY"].SummaryItem.DisplayFormat = "{0:N}";
                //初始化为空
                this.gridView1.Columns["PRODUCTIVITY"].SummaryItem.SetSummary
                        (DevExpress.Data.SummaryItemType.Sum, "");
                if (Convert.ToDecimal(this.gridView1.Columns["WORK_HOURS"].SummaryItem.SummaryValue) > 0)
                    this.gridView1.Columns["PRODUCTIVITY"].SummaryItem.SetSummary
                        (DevExpress.Data.SummaryItemType.Sum,
                       Math.Round((Convert.ToDecimal(this.gridView1.Columns["ALUMINIUM_QTY"].SummaryItem.SummaryValue) +
                        // Convert.ToDecimal(this.gridView1.Columns["METAL_CABINET_QTY"].SummaryItem.SummaryValue) +
                        Convert.ToDecimal(this.gridView1.Columns["MC_CONVERT_QTY"].SummaryItem.SummaryValue)) /
                        Convert.ToDecimal(this.gridView1.Columns["WORK_HOURS"].SummaryItem.SummaryValue), 2).ToString());
            }
        }

        private void btnPFChange_Click(object sender, EventArgs e)
        {
            // MdiTools.OpenChildWebBrowse(this.MdiParent as IMdiForm, new frmBaseChildWinForm("MCG_PowderCoating_Type_Adjust", 1, true, false), sender as ToolStripMenuItem);

            DataTable dt = BaseBuildSql.GetDataTableBySql("select *　from　sys_menu where winformid='menuPDT_MCG_Powder_Coating_Type'");
            MdiTools.OpenChildForm_Param(this.MdiParent as IMdiForm, new frmBaseChildWinForm("MCG_PowderCoating_Type_Adjust", 0, true, false), dt.Rows[0]["id"].ToString());

        }
        public override void DoExport(IButtonInfo sender)
        {
            if (!Directory.Exists(@"D:\MESTemp"))
                Directory.CreateDirectory(@"D:\MESTemp");
            //本地存储位置
            string path = @"D:\MESTemp\MCG_Powder_" + DateTime.Now.ToString("yyyyMMdd_hhmmss") + ".xlsx";


            //列头转换成中文
            DataTable table1 = Common.GetTable.GetTable_Chinese1(Table_Sum);
            DataTable table2 = Common.GetTable.GetTable_Chinese2(Table_Detail);

            if (table1 != null || table2 != null)
            {
                if (Common.ExcelHelpers.DataTableToExcel(table1, table2, path))
                {
                    if (DevExpress.XtraEditors.XtraMessageBox.Show("导出成功，是否打开文件？", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
                        System.Diagnostics.Process.Start(path);//打开指定路径下的文件
                }
            }
        }
        //审批
        public override void DoApproval(IButtonInfo sender)
        {
            try
            {
                string strStart = txtStart.Text;
                string strEnd = txtEnd.Text;
                HNI_Months = dateEdit1.Text;
                if (string.IsNullOrEmpty(HNI_Months) || string.IsNullOrEmpty(strStart) || string.IsNullOrEmpty(strEnd))
                {
                    DevExpress.XtraEditors.XtraMessageBox.Show("HNI时间不允许为空！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
                if (Table_Sum == null || Table_Sum.Rows.Count <= 0)
                {
                    XtraMessageBox.Show("请先刷新当前HNI月数据！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
                if (Common.CURDHelper.GetTable_Productivity_History(HNI_Months).Rows.Count <= 0)
                {
                    XtraMessageBox.Show("当前HNI月数据未申报,不需要审批！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
                SplashScreenTool.ShowSplashScreen(typeof(WaitForm1));
                //审批
                if (Common.CURDHelper.Update_History(HNI_Months))
                {
                    if (!Directory.Exists(@"D:\MESTemp"))
                        Directory.CreateDirectory(@"D:\MESTemp");
                    //本地存储位置
                    string path = @"D:\MESTemp\喷粉生产力_" + HNI_Months + ".xlsx";
                    string strname = HNI_Months.Substring(0, 4) + "年" + HNI_Months.Substring(4, 2) + "月";

                    DataTable table1 = Common.GetTable.GetTable_Chinese1(Table_Sum);
                    DataTable table2 = Common.GetTable.GetTable_Chinese2(Table_Detail);
                    if (Common.ExcelHelpers.DataTableToExcel(table1, table2, path))
                    {
                        string[] strAdress = { "Shaofen.Lin@lamex.com.hk" };
                        string[] strCC = { "bess.chong@lamex.com.hk", "Weihua.Deng@lamex.com.hk" };//抄送
                        //string[] strAdress = { "Bill.Luo@lamex.com.hk" };
                        //string[] strCC = null;
                        Common.MailHelper.SendMailUseGmail_Approval(strname, path, strAdress, strCC);
                        XtraMessageBox.Show("审批成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                }
                else
                {
                    XtraMessageBox.Show("该月数据已审批,不需要再次审批！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                SplashScreenTool.CloseSplashScreen();
            }

            catch (Exception ex)
            {
                SplashScreenTool.CloseSplashScreen();
                XtraMessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;

            }

        }
        //申报
        public override void DoDeclare(IButtonInfo sender)
        {
            try
            {
                string strStart = txtStart.Text;
                string strEnd = txtEnd.Text;
                HNI_Months = dateEdit1.Text;
                if (string.IsNullOrEmpty(HNI_Months) || string.IsNullOrEmpty(strStart) || string.IsNullOrEmpty(strEnd))
                {
                    DevExpress.XtraEditors.XtraMessageBox.Show("HNI时间不允许为空！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
                if (Table_Sum == null || Table_Sum.Rows.Count <= 0)
                {
                    XtraMessageBox.Show("请先刷新当前HNI月数据！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }

                DataTable table = new DataTable();
                table = Table_Sum.Copy();
                DataColumn dc1 = new DataColumn("YEAR_MONTH", typeof(string));
                dc1.DefaultValue = HNI_Months;
                DataColumn dc2 = new DataColumn("UPDATE_TIME", typeof(string));
                dc2.DefaultValue = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
                DataColumn dc3 = new DataColumn("UPDATE_USER", typeof(string));
                dc3.DefaultValue = Lamex.Common.Loginer.CurrentUser.AccountName;
                table.Columns.Add(dc1);
                table.Columns.Add(dc2);
                table.Columns.Add(dc3);
                //判断是否存在当月的HNI数据
                if (Common.CURDHelper.GetTable_Productivity_History(HNI_Months).Rows.Count > 0)
                {
                    XtraMessageBox.Show("当前HNI月数据已申报,不允许重复申报！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
                SplashScreenTool.ShowSplashScreen(typeof(WaitForm1));
                if (BaseBuildSql.ExcuteInsert(table, "MCG_PowderCoating_Productivity_History"))
                {
                    string strname = HNI_Months.Substring(0, 4) + "年" + HNI_Months.Substring(4, 2) + "月";
                    //string[] strAdress = { "Bill.Luo@lamex.com.hk" };
                    //string[] strCC = null;
                    string[] strAdress = { "ty.chan@lamex.com.hk" };
                    string[] strCC = null; //{ "Weihua.Deng@lamex.com.hk" };//抄送
                    Common.MailHelper.SendMailUseGmail(strname, txtQty.Text, strAdress, strCC);
                    XtraMessageBox.Show("申报成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);

                }
                else
                {
                    XtraMessageBox.Show("申报失败！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                SplashScreenTool.CloseSplashScreen();

            }
            catch (Exception ex)
            {
                SplashScreenTool.CloseSplashScreen();
                XtraMessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
        //退回
        public override void DoBack(IButtonInfo sender)
        {
            try
            {

                string strStart = txtStart.Text;
                string strEnd = txtEnd.Text;
                HNI_Months = dateEdit1.Text;
                if (string.IsNullOrEmpty(HNI_Months) || string.IsNullOrEmpty(strStart) || string.IsNullOrEmpty(strEnd))
                {
                    DevExpress.XtraEditors.XtraMessageBox.Show("HNI时间不允许为空！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
                if (Table_Sum == null || Table_Sum.Rows.Count <= 0)
                {
                    XtraMessageBox.Show("请先刷新当前HNI月数据！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
                if (Common.CURDHelper.GetTable_Productivity_History(HNI_Months).Rows.Count <= 0)
                {
                    XtraMessageBox.Show("当前HNI月数据未申报,不需要退回！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
                SplashScreenTool.ShowSplashScreen(typeof(WaitForm1));
                //退回
                if (Common.CURDHelper.Delete_History(HNI_Months))
                {
                    XtraMessageBox.Show("退回成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                SplashScreenTool.CloseSplashScreen();
            }

            catch (Exception ex)
            {
                SplashScreenTool.CloseSplashScreen();
                XtraMessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;

            }

        }
    }
}
